package com.ken.common.auth.interception;

import com.ken.ability.auth.protocol.security.AuthUserDetails;
import com.ken.common.core.utils.AuthLocal;
import com.ken.common.core.utils.BeanCopyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Component
@Slf4j
public class AuthInterception extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("[Auth-Interception] - 认证拦截器触发");
        Optional.ofNullable(AuthLocal.getUser())
                .map(authUser -> {
                    AuthUserDetails authUserDetails = BeanCopyUtils.copyBean(authUser, AuthUserDetails.class);
                    return authUserDetails;
                })
                .ifPresent(authUserDetails -> {
                    //如果登录用户不为空，这
                    UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                            = new UsernamePasswordAuthenticationToken(authUserDetails, null, authUserDetails.getAuthorities());
                    SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);
                    log.debug("[Auth-Interception] - 认证拦截器设置当前身份信息 - {}", authUserDetails);
                });
        return super.preHandle(request, response, handler);
    }
}
